package c_007;

import java.util.concurrent.TimeUnit;

/**
 * synchronized优化
 * 同步代码块语句越少越好
 */
public class T03 {

    int count = 0;

    synchronized void m1(){
        //do sth not need sync
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //业务逻辑代码只有下面这句需要sync
        count++;

        //do sth not need sync
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    void m2(){
        //do sth not need sync
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //业务逻辑代码只有下面这句需要sync
        //采用细粒度锁,可以使线程争用时间减少,从而提高效率
        synchronized (this){
            count++;
        }

        //do sth not need sync
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}

//锁粗化场景--当一部分代码块锁有点多,不如直接锁整块,锁的争用反而就不那么频繁了